package com.xj.listener;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @version 1.0
 * @program: demo2
 * @packageName: com.xj.listener
 * @className XjConsumerListener
 * @description: TODO
 * @author: xj
 * @create: 2021-01-11 15:15:26
 **/

@Component
@RocketMQTransactionListener()
public class XjTxProducerListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        System.out.println("开始执行本地事务的execute方法");
        try {
            String msgBody = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            String localArg = (String) o;

            System.out.println("事务消息的消息体为："+msgBody+": 本地事务参数："+localArg);
        } catch (Exception e) {
            System.out.println("执行本地事务发生异常："+e);
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        System.out.println("结束执行本地事务的execute方法");
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        System.out.println("开始执行本地事务的检查check方法");
        try {
            String msgBody = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            System.out.println("事务消息的消息体为："+msgBody);

        } catch (Exception e) {
            System.out.println("执行本地事务的check发生异常："+e);
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        System.out.println("结束执行本地事务的检查check方法");
        return RocketMQLocalTransactionState.COMMIT;
    }
}
